package com.yxn.base;

/**
 * Created by yanxi on 2018/1/13 0013.
 */

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;

/**
 * 将数据库的增删改查操作实现并直接操作数据库
 * @author sivan.l
 *
 * @param <T>
 */
public abstract class HibernateDao<T> implements BaseDao<T>{

    @Autowired
    private SessionFactory sessionFactory;
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    @Override
    public Serializable add(T t) {
        return sessionFactory.getCurrentSession().save(t);
    }

    @Override
    public void update(T t) {
        sessionFactory.getCurrentSession().update(t);
    }

    @Override
    public int delete(Serializable id) {
        String hql = "delete from "+this.getEntityClass().getSimpleName()+" en where en.id = ?";
        return sessionFactory.getCurrentSession().createQuery(hql).setParameter(0, id).executeUpdate();
    }

    @Override
    public void delete(T t) {
        sessionFactory.getCurrentSession().delete(t);
    }

    @SuppressWarnings("unchecked")
    @Override
    public T findDataById(Serializable id) {
        return (T) sessionFactory.getCurrentSession().get(getEntityClass(), id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> findDataByCondition(String conditionName, String conditionValue, String conditionOperation) {
        String hql = "select en from "+getEntityClass().getSimpleName()+" en where en."+conditionName+" "+conditionOperation+"?";
        return sessionFactory.getCurrentSession().createQuery(hql).setParameter(0, conditionValue).list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> findDataByPage(int pageNum, int pageCount) {
        String hql = "from "+getEntityClass().getSimpleName();
        return sessionFactory.getCurrentSession().createQuery(hql).setFirstResult((pageNum-1)*pageCount).setMaxResults(pageCount).list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> findAllData() {
        String hql = "from "+getEntityClass().getSimpleName();
        return sessionFactory.getCurrentSession().createQuery(hql).list();
    }

    protected abstract Class<T> getEntityClass();

}
